package VideoProcessing;

import java.awt.image.WritableRaster;

import javax.media.Format;
import javax.media.format.RGBFormat;
import javax.media.format.VideoFormat;

public class RgbDiffEffect extends RgbVideoEffect {

	private BackgroundUpdater bgUpdater;

	public RgbDiffEffect(BackgroundUpdater bgUpdater) {
		supportedIns = new Format[] { new RGBFormat() };
		supportedOuts = new Format[] { new RGBFormat() };
		this.bgUpdater = bgUpdater;
	}

	public String getName() {
		return "RGB-Difference from Background Image";
	}

	protected boolean processRGB(byte[] bin, byte[] bout, VideoFormat format) {
		if (bgUpdater.getBackground() != null) {
			// // Calculate difference between input and background
			int now, before, diff;
			// long totalAmt = 0;
			byte[] background = bgUpdater.getBackground();
			for (int i = 0; i < bin.length; i++) {
				now = byte2Int(bin[i]);
				before = byte2Int(background[i]);
				diff = Math.abs(now - before);
				bout[i] = (byte) (diff);
			}

		} else {
			// // Make output show no differences
			for (int i = 0; i < bin.length; i++) {
				bout[i] = 0;
			}
		}
		return true;
	}

	protected void updateImage(byte[] bout, VideoFormat vformat) {
		synchronized (displayImage) {
			// // Copy pixels to image
			WritableRaster rast = displayImage.getRaster();
			int[] pixel = new int[] { 0, 0, 0, 255 };
			int p = 0;
			for (int y = vformat.getSize().height - 1; y >= 0; y--) {
				for (int x = 0; x < vformat.getSize().width; x++) {
					pixel[0] = pixel[1] = pixel[2] = bout[p++];
					rast.setPixel(x, y, pixel);
				}
			}
		}
	}
}
